import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'

Vue.use(Router)

// 解决两次访问相同路由地址报错
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
	return originalPush.call(this, location).catch(err => err)
}

const router = new Router({
	mode: "history",
	routes: [{
			path: '/',
			redirect: '/index'
		},
		{
			path: '/index',
			name: 'Index',
			component: () => import('../views/layout/Index.vue'),
			redirect: '/project',
			children: [{
					path: '/project',
					name: 'project',
					component: () => import('../views/project/Index.vue'),
					meta: {
						title: ['我的项目']
					}
				},
                {
                	path: '/project/kv/items',
                	name: 'keyValues',
                	component: () => import('../views/key_value/Index.vue'),
                	meta: {
                		title: ['项目配置']
                	}
                },
				{
					path: '/users',
					name: 'users',
					component: () => import('../views/user/Index.vue'),
					meta: {
						title: ['用户管理']
					}
				},
				{
					path: '/changepwd',
					name: 'changepwd',
					component: () => import('../views/mine/ChangePwd.vue'),
					meta: {
						title: ['修改密码']
					}
				},
			]
		},
		{
			path: '/login',
			name: 'login',
			component: () => import('../views/login/Index.vue'),
			meta: {
				anonymous: true,
				title: ['登录']
			}
		},
		{
			path: '/lock',
			name: 'lock',
			component: () => import('../views/Lock.vue'),
			meta: {
				title: ['锁定']
			}
		},
		{
			path: '*',
			name: 'notfound',
			component: () => import('../views/404.vue'),
			meta: {
				anonymous: true,
				title: ['找不到访问页面']
			}
		},
	]
})

// 路由守卫
router.beforeEach((to, from, next) => {
	store.dispatch('setHeaderTitle', to.meta.title);
	if (to.meta.anonymous || store.getters.isAuthenticated) {
		next();
	} else {
		next({path: '/login', query: {rt: to.fullPath }});
	}
})

export default router
